const dayjs = require('dayjs');
// projects/oa/pages/knowledge/edit/knowledge_edit.js
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper, timerHelper } = pathImport;;
const { logEvent } = require('../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../helpers/network_helper.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		id: '', // 文档ID，编辑时使用
		
		// 表单数据
		formData: {
			title: '',
			content: '',
			attachments: [],
			assignee: '', // 指定的同事
			assigneeId: '', // 指定同事的ID
			status: 'draft' // 状态：草稿(draft)、已指派(assigned)、已完成(completed)
		},

		// 分类选项
		categories: [
			{ value: 'tech', text: '技术文档' },
			{ value: 'product', text: '产品文档' },
			{ value: 'design', text: '设计规范' },
			{ value: 'api', text: 'API文档' },
			{ value: 'qa', text: 'Q&A' }
		],
		categoryIndex: 0,

		// 同事选择相关
		userList: [],
		userIndex: -1,

		submitting: false
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		if (!PassportBiz.isLogin()) {
			wx.showModal({
				title: '提示',
				content: '请先登录',
				showCancel: false,
				success: () => {
					wx.navigateBack();
				}
			});
			return;
		}

		// 设置页面标题
		if (options.id) {
			this.setData({ id: options.id });
			wx.setNavigationBarTitle({
				title: '编辑知识库'
			});
			await this._loadDocument(options.id);
		} else {
			wx.setNavigationBarTitle({
				title: '新建知识库'
			});
		}
		
		// 加载用户列表
		await this._loadUserList();

		// 网络检测
		const net = await getNetworkStatus();
		if (!net.isConnected) {
			wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
		} else if (net.networkType === '2g') {
			wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
		}
		listenNetworkStatus((res) => {
			if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
			else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
		});
		logEvent('page_load', { page: 'knowledge_edit' });

		this.setData({ isLoad: true });
	},

	/**
	 * 加载用户列表
	 */
	async _loadUserList() {
		try {
			const result = await cloudHelper.callCloudData('home/contact_list', {});
			
			// 扁平化所有联系人到一个数组
			let userList = [];
			if (result && result.data) {
				result.data.forEach(dept => {
					if (dept.users && dept.users.length > 0) {
						dept.users.forEach(user => {
							userList.push({
								id: user.id,
								name: user.name,
								dept: dept.dept,
								displayName: `${user.name}（${dept.dept}）`
							});
						});
					}
				});
			}
			
			this.setData({ userList });
		} catch (err) {
			console.error('获取用户列表失败', err);
		}
	},

	/**
	 * 加载文档数据
	 */
	async _loadDocument(id) {
		try {
			const doc = await cloudHelper.callCloudData('knowledge/detail', { id });
			if (!doc) return;

			// 设置表单数据
			const categoryIndex = this.data.categories.findIndex(c => c.value === doc.category);
			
			// 找到指定的用户索引
			let userIndex = -1;
			if (doc.assigneeId) {
				userIndex = this.data.userList.findIndex(u => u.id === doc.assigneeId);
			}
			
			this.setData({
				formData: {
					title: doc.title,
					content: doc.content,
					attachments: doc.attachments || [],
					assignee: doc.assignee || '',
					assigneeId: doc.assigneeId || '',
					status: doc.status || 'draft'
				},
				categoryIndex: categoryIndex > -1 ? categoryIndex : 0,
				userIndex: userIndex
			});
		} catch (err) {
			console.error('加载文档失败：', err);
			pageHelper.showModal('加载失败，请重试');
		}
	},

	/**
	 * 分类选择改变
	 */
	onCategoryChange(e) {
		this.setData({
			categoryIndex: e.detail.value
		});
	},

	/**
	 * 编辑器工具点击
	 */
	onToolTap(e) {
		const type = e.currentTarget.dataset.type;
		let content = this.data.formData.content;
		const selection = this._getSelection();

		// 切换工具栏激活状态
		const editorTools = this.data.editorTools.map(item => {
			if (item.type === type) {
				// 对于bold, italic, underline这类格式化工具可以切换状态
				if(['bold', 'italic', 'underline'].includes(type)) {
					return {...item, active: !item.active};
				}
				// 对于其他工具只是临时激活
				return {...item, active: true};
			} else if(!['bold', 'italic', 'underline'].includes(item.type)) {
				// 非格式化工具都重置为非激活
				return {...item, active: false};
			}
			return item;
		});

		switch (type) {
			case 'bold':
				content = this._insertText(content, selection, '**', '**');
				break;
			case 'italic':
				content = this._insertText(content, selection, '_', '_');
				break;
			case 'underline':
				content = this._insertText(content, selection, '<u>', '</u>');
				break;
			case 'header':
				content = this._insertText(content, selection, '## ', '');
				break;
			case 'list':
				content = this._insertText(content, selection, '- ', '');
				break;
			case 'link':
				content = this._insertText(content, selection, '[', '](url)');
				break;
			case 'image':
				this.chooseImage();
				break;
		}

		this.setData({
			'formData.content': content,
			editorTools
		});

		// 对于非持久状态的工具，1秒后自动取消激活状态
		if(!['bold', 'italic', 'underline'].includes(type)) {
			setTimeout(() => {
				const resetTools = this.data.editorTools.map(item => {
					if(item.type === type) {
						return {...item, active: false};
					}
					return item;
				});
				this.setData({
					editorTools: resetTools
				});
			}, 1000);
		}
	},

	/**
	 * 获取选中文本
	 */
	_getSelection() {
		// 由于小程序限制，无法获取真实的选中文本
		// 这里返回一个空对象，实际项目中可以使用其他方式实现
		return {
			start: 0,
			end: 0,
			text: ''
		};
	},

	/**
	 * 插入文本
	 */
	_insertText(content, selection, prefix, suffix) {
		const start = selection.start;
		const end = selection.end;
		const text = selection.text;

		if (text) {
			return content.substring(0, start) + prefix + text + suffix + content.substring(end);
		} else {
			return content + prefix + suffix;
		}
	},

	/**
	 * 选择图片
	 */
	async chooseImage() {
		try {
			const res = await wx.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera']
			});

			wx.showLoading({ title: '上传中...' });
			const result = await cloudHelper.uploadFile(res.tempFilePaths[0], 'knowledge');
			
			const content = this.data.formData.content + `\n![图片](${result.fileID})`;
			this.setData({
				'formData.content': content
			});
		} catch (err) {
			console.error('上传图片失败：', err);
			pageHelper.showModal('上传失败，请重试');
		} finally {
			wx.hideLoading();
		}
	},

	/**
	 * 选择文件
	 */
	async chooseFile() {
		try {
			const res = await wx.chooseMessageFile({
				count: 1,
				type: 'file'
			});

			const file = res.tempFiles[0];
			if (file.size > 10 * 1024 * 1024) {
				pageHelper.showModal('文件大小不能超过10MB');
				return;
			}

			wx.showLoading({ title: '上传中...' });
			const result = await cloudHelper.uploadFile(file.path, 'knowledge');
			
			const attachments = this.data.formData.attachments;
			attachments.push({
				tempId: dayjs().valueOf(),
				name: file.name,
				size: pageHelper.formatFileSize(file.size),
				fileID: result.fileID
			});

			this.setData({
				'formData.attachments': attachments
			});
		} catch (err) {
			console.error('上传文件失败：', err);
			pageHelper.showModal('上传失败，请重试');
		} finally {
			wx.hideLoading();
		}
	},

	/**
	 * 移除附件
	 */
	removeAttachment(e) {
		const tempId = e.currentTarget.dataset.id;
		const attachments = this.data.formData.attachments.filter(item => item.tempId !== tempId);
		this.setData({
			'formData.attachments': attachments
		});
	},

	/**
	 * 同事选择改变
	 */
	onUserChange(e) {
		const index = parseInt(e.detail.value);
		if (index >= 0 && index < this.data.userList.length) {
			const user = this.data.userList[index];
			this.setData({
				userIndex: index,
				'formData.assignee': user.name,
				'formData.assigneeId': user.id
			});
		}
	},
	
	/**
	 * 清除指定同事
	 */
	clearAssignee() {
		this.setData({
			userIndex: -1,
			'formData.assignee': '',
			'formData.assigneeId': ''
		});
	},

	/**
	 * 表单提交
	 */
	async formSubmit(e) {
		if (this.data.submitting) return;

		const formData = e.detail.value;
		if (!formData.title?.trim()) {
			pageHelper.showModal('请输入文档标题');
			return;
		}
		if (!formData.content?.trim()) {
			pageHelper.showModal('请输入文档内容');
			return;
		}

		this.setData({ submitting: true });

		try {
			const data = {
				id: this.data.id || `doc_${dayjs().valueOf()}`,
				title: formData.title,
				content: formData.content,
				category: this.data.categories[this.data.categoryIndex].value,
				categoryText: this.data.categories[this.data.categoryIndex].text,
				attachments: this.data.formData.attachments,
				assignee: this.data.formData.assignee,
				assigneeId: this.data.formData.assigneeId,
				status: this.data.formData.assigneeId ? 'assigned' : 'draft',
				author: {
					name: '当前用户', // 理想情况下应该从用户信息中获取
					avatar: '/projects/oa/images/tabbar/my.png'
				},
				updateTime: dayjs().toISOString().split('T')[0],
				views: 0,
				likes: 0
			};

			// 获取现有文档列表
			let documents = wx.getStorageSync('local_knowledge_docs') || [];
			
			if (this.data.id) {
				// 编辑现有文档
				const index = documents.findIndex(doc => doc.id === this.data.id);
				if (index >= 0) {
					documents[index] = {...documents[index], ...data};
				} else {
					documents.push(data);
				}
			} else {
				// 添加新文档
				documents.push(data);
			}
			
			// 保存到本地存储
			wx.setStorageSync('local_knowledge_docs', documents);
			
			// 如果指定了同事，添加本地消息通知
			if (data.assigneeId) {
				this._addLocalNotification(data);
				
				wx.showModal({
					title: '指派成功',
					content: `已将文档指派给 ${data.assignee}。\n(消息已添加到工作台通知区)`,
					showCancel: false
				});
			} else {
				wx.showToast({
					title: '保存成功',
					icon: 'success'
				});
			}

			timerHelper.setTimeout(this, 'timeout_navigate', () => {
				wx.navigateBack();
			}, 1500);
		} catch (err) {
			console.error('保存失败：', err);
			pageHelper.showModal('保存失败，请重试');
		} finally {
			this.setData({ submitting: false });
		}
	},

	/**
	 * 添加本地消息通知
	 */
	_addLocalNotification(document) {
		// 获取现有通知列表
		let notifications = wx.getStorageSync('local_notifications') || [];
		
		// 创建新通知
		const notification = {
			id: `notif_${dayjs().valueOf()}`,
			title: '您有一个待完成的知识文档',
			content: `您被指定完成《${document.title}》文档，请尽快处理。`,
			type: 'knowledge',
			status: 'unread',
			createTime: dayjs().toISOString(),
			docId: document.id,
			path: `/projects/oa/pages/knowledge/edit/knowledge_edit?id=${document.id}`
		};
		
		// 添加到通知列表
		notifications.unshift(notification);
		
		// 保存到本地存储
		wx.setStorageSync('local_notifications', notifications);
		
		// 更新未读消息数
		this._updateUnreadCount();
	},

	/**
	 * 更新未读消息数
	 */
	_updateUnreadCount() {
		const notifications = wx.getStorageSync('local_notifications') || [];
		const unreadCount = notifications.filter(n => n.status === 'unread').length;
		wx.setStorageSync('unread_notification_count', unreadCount);
		
		// 设置消息红点
		if (unreadCount > 0) {
			wx.showTabBarRedDot({
				index: 0 // 工作台tabBar索引，根据实际情况调整
			});
		}
	},

	/**
	 * 取消
	 */
	onCancel() {
		wx.navigateBack();
	},

	/**
	 * 标题输入事件
	 */
	onTitleInput(e) {
		this.setData({
			'formData.title': e.detail.value
		});
	},

	/**
	 * 内容输入事件
	 */
	onContentInput(e) {
		this.setData({
			'formData.content': e.detail.value
		});
	},
})